<template>
  <div>
    <Modal v-model="modals" height="900" :styles="{ height: '80%' }" width="800" scrollable footer-hide closable
      :title="titleFrom" :z-index="1" @on-cancel="handleReset" class-name="vertical-center-modal">
      <Form ref="formValidate" :model="formValidate" :label-width="110" :rules="ruleValidate" @submit.native.prevent>
        <Col v-bind="grid">
        <FormItem label="区域：">
          <Radio-group v-model="formValidate.warehouse_id" @on-change="clickRadio">
            <Radio label="1">一号</Radio>
            <Radio label="3">三号</Radio>
          </Radio-group>
        </FormItem>
        </Col>
        <Col v-bind="grid">
        <FormItem label="位置：">
          <CheckboxGroup v-model="selectLocation" @on-change="debouncedClickCheckbox">
            <Checkbox :label="item.location" v-for="item in exhibitionList"
              :disabled="item.is_select && !selfSelectLocation.includes(item.location)" :key="item.id">{{ item.location
              }}({{ item.square }}㎡)</Checkbox>
          </CheckboxGroup>
        </FormItem>
        </Col>
        <col>
        <div v-if="itemRegion == 1"
          style="width: 70%; height: 300px;margin: auto; display: flex; justify-content: flex-end;">
          <img src="@/assets/img/Booth1.png" alt="" style="width: 100%; height: 100%;">
        </div>
        <div v-if="itemRegion == 3"
          style="width: 100%; height: 200px;margin: auto; display: flex; justify-content: flex-end;">
          <img src="@/assets/img/Booth3.png" alt="" style="width: 100%; height: 100%;">
        </div>
        </col>
        <col>
        <FormItem label="布置模板：">
          <div v-if="templatePic" style="width: 100%; height: 100%;">
            <img style="width: 100%; height: 100%;" :src="templatePic" alt="">
          </div>
        </FormItem>
        </col>
        <Col>
        <FormItem label="是否完成: ">
          <Radio-group v-model="isComfirmRadio">
            <Radio label="是">是</Radio>
            <Radio label="否">否</Radio>
          </Radio-group>
        </FormItem>
        </Col>
        <col>
        <FormItem label="图片：">
          <div class="demo-upload-list" v-for="item in uploadList">
            <template v-if="item.status === 'finished'">
              <img :src="item.url">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload ref="upload" :show-upload-list="false" :default-file-list="defaultList" :on-success="handleSuccess"
            :format="['jpg', 'jpeg', 'png']" :max-size="2048" :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload" multiple type="drag" :action="fileUrl"
            style="display: inline-block;width:58px;" :headers="header" :on-error="handleError">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <Modal title="View Image" v-model="visible">
            <img :src="imgName" v-if="visible" style="width: 100%">
          </Modal>
        </FormItem>
        </col>
        <Col v-bind="grid">
        <FormItem label="尺寸(长 * 宽 ㎡)：" prop="size">
          <Input v-model="formValidate.size" maxlength="20" show-word-limit placeholder="请输入尺寸" prop=""></Input>
        </FormItem>
        </Col>
        <Col span="24">
        <div class="style-add">
          <Button class="mr14" type="default" @click="cancle">取消</Button>
          <Button type="primary" @click="isComfirm" v-auth="['admin-supplier-exhibition-edit']">确认</Button>
        </div>
        </Col>
      </Form>
    </Modal>
    <comfiem ref="comfiem" @confirm="handleSubmit('formValidate')" />
  </div>
</template>

<script>
import { createStoreWarehouseExhibition, supplierExhibitionList } from "@api/warehouseExhibition";
import comfiem from './comfiem.vue'
import util from "@/libs/util";
const debounce = (fn, delay) => {
  // 将 timer 定义在闭包内，每个防抖函数都有自己独立的 timer
  let timer = null;
  return function (...args) {
    // 清除上一个定时器
    clearTimeout(timer);
    // 创建新的定时器
    timer = setTimeout(() => {
      fn.apply(this, args);
      // 执行完毕后，将 timer 清空，确保状态干净
      timer = null;
    }, delay);
  };
};
export default {
  name: "menusFrom",
  props: {
    formValidate: {
      type: Object,
      default: null,
    },
    fromName: {
      type: Number,
      default: 0
    }
  },
  components: {
    comfiem
  },
  data() {
    return {
      ruleValidate: {
        brand_name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
      },
      templatePic: '',
      confirmModal: false,
      type: 1,
      modals: false,
      // authType:false,
      selectLocation: [],
      FromData: [],
      exhibitionList: [],
      titleFrom: '',
      selfSelectLocation: [],
      grid: {
        xl: 24,
        lg: 24,
        md: 12,
        sm: 24,
        xs: 24,
      },
      fileUrl: "http://dev.supplier.vanitii-global.com/adminapi/file/upload",
      diffArr: [],
      // 用于存储已选中的位置
      itemRegion: 3,
      isComfirmRadio: '否',
      defaultList: [
        // {
        //   // 'name': 'image-demo-1.jpg',
        //   'url': 'http://dev.supplier.vanitii-global.com/uploads/file/852488ddd9570bc877783bf4397563e0_20250822163857.png'
        // }
      ],
      imgName: '',
      visible: false,
      uploadList: [],
      header: {},
    }
  },
  created() {
    this.debouncedClickCheckbox = debounce(this.clickCheckbox, 200);
  },
  mounted() {
    this.getToken();
  },
  methods: {
    templatePicInit() {
      this.isComfirmRadio = this.formValidate.is_arrangement == 1 ? '是' : '否';
      if (this.formValidate.file_url) {
        this.templatePic = this.formValidate.file_url;
      } else {
        this.templatePic = '';
      }
    },
    getToken() {
      this.header["Authori-zation"] = "Bearer " + util.cookies.get("token");
    },
    handleError(res, file, fileList) {
      alert(res.msg || '文件太大了，上传失败,2M以内');
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess(res, file, fileList) {
      console.log(res, file, fileList, 'res, file');
      file.url = res.data.src;
      file.name = res.data.file;
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
      });
    },
    handleMaxSize(file) {
      alert('File  ' + file.name + ' is too large, no more than 2M.');
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File  ' + file.name + ' is too large, no more than 2M.'
      });
    },
    handleBeforeUpload() {
      const check = this.uploadList.length < 5;
      if (!check) {
        this.$Notice.warning({
          title: 'Up to five pictures can be uploaded.'
        });
      }
      return check;
    },
    initVal() {
      // 初始化已选中的location集合
      const initSelectedLocations = this.exhibitionList
        .filter(item => item.is_select)
        .map(item => item.location);
      // 解析store_warehouse_exhibition_id为数组
      let storeIds = [];
      if (Array.isArray(this.formValidate.store_warehouse_exhibition_id)) {
        storeIds = this.formValidate.store_warehouse_exhibition_id;
      } else if (typeof this.formValidate.store_warehouse_exhibition_id === 'string' && this.formValidate.store_warehouse_exhibition_id) {
        try {
          storeIds = JSON.parse(this.formValidate.store_warehouse_exhibition_id);
        } catch (e) {
          storeIds = [];
        }
      }
      // 对比，得到不同项
      const diffArr = [...initSelectedLocations.filter(x => !storeIds.includes(x)), ...storeIds.filter(x => !initSelectedLocations.includes(x))];
      this.diffArr = diffArr; // 保存到data中，供clickCheckbox使用
    },
    clickCheckbox(val) {
      // val 是当前选中的location数组
      // selectedLocations 是之前已选中的location数组
      const selectedLocations = Array.isArray(this.diffArr) ? this.diffArr : [];
      // 找出val中有但selectedLocations没有的（新增）
      const added = val.filter(loc => !selectedLocations.includes(loc));
      // 找出selectedLocations中有但val没有的（删除）
      const removed = selectedLocations.filter(loc => !val.includes(loc));
      // 合并新增和删除的差异项
      const diffArr = Array.from(new Set([...added, ...removed]));
      this.formValidate.store_warehouse_exhibition_id = diffArr;
    },
    initUploadPic(){
      this.$refs.upload.fileList = []
      this.uploadList = []
      let urls;
      if( this.formValidate &&this.formValidate.layout_file_url){
         urls = JSON.parse(this.formValidate.layout_file_url);
            console.log(urls,'urls');
            if (Array.isArray(urls)) {
              this.$refs.upload.fileList = urls.map(url => ({
                url,
                status: "finished"
               }));
            } else {
              this.$refs.upload.fileList = [];
            }
             };
            console.log('this.$refs.upload.fileList', this.$refs.upload.fileList);
            this.uploadList = this.$refs.upload.fileList;
    },
    clickRadio(region) {
      this.itemRegion = region
      supplierExhibitionList({ region: region }).then(async (res) => {
        this.exhibitionList = res.data
        this.exhibitionList.forEach(item => {
          if (item.is_select) {
            this.selectLocation.push(item.location)
          }
        })
        this.initVal()
        this.templatePicInit();
        this.initUploadPic()
      }).catch((err) => {
        this.$Message.error(err && err.msg ? err.msg : (err && err.message ? err.message : '请求失败'));
      });
    },
    handleReset() {
      this.selectLocation = []
      this.$refs.upload.fileList = []
      this.modals = false;
      this.$parent.getData()
    },
    isComfirm() {
      this.$refs.comfiem.modal = true
      const res = this.formValidate.store_warehouse_exhibition_id || selfSelectLocation
      this.$refs.comfiem.text = res
    },
    handleSubmit(name) {
      let layout_file_url = []
      if (this.uploadList.length > 0) {
        this.uploadList.forEach(item => {
          layout_file_url.push(item.url)
        })
      }
      this.isComfirmRadio == '是' ? this.formValidate.is_arrangement = 1 : this.formValidate.is_arrangement = 0
      this.formValidate.layout_file_url = layout_file_url
      const value = this.formValidate.store_warehouse_exhibition_id;
      if (value != null && !Array.isArray(value) && typeof value === "string") {
        try {
          this.formValidate.store_warehouse_exhibition_id = JSON.parse(value);
        } catch (e) {
          console.error("JSON 解析失败", e);
          // 可以选择赋默认值，如：this.formValidate.store_warehouse_exhibition_id = [];
        }
      }
      this.$refs.upload.fileList = []
      this.selectLocation = []
      this.$refs[name].validate((valid) => {
        if (valid) {
          createStoreWarehouseExhibition(this.formValidate).then(res => {
            this.$Message.success(res.msg)
            this.$parent.getSupplier()
            this.modals = false
          }).catch(err => {
            this.$Message.error(err.msg)
          })
        } else {
          this.$Message.error('请输入品牌名称');
        }
      })
    },
    cancle() {
      this.selectLocation = []
      this.$refs.upload.fileList = []
      this.modals = false
    }
  },
  watch: {
    formValidate: {
      handler(newVal, oldVal) {
        newVal.store_warehouse_exhibition_id == 'null' && (newVal.store_warehouse_exhibition_id = [])
        if (newVal.store_warehouse_exhibition_id) {
          this.selfSelectLocation = JSON.parse(newVal.store_warehouse_exhibition_id);
        } else {
          this.selfSelectLocation = []
        }
      },
      deep: true
    }
  }

};
</script>

<style scoped lang="stylus">
 .style-add {
 display:flex;
 justify-content: flex-end;
 }
 .mr14 {
  margin-right:14px
 }
  /deep/.ivu-cascader-menu{
    height: auto;
    max-height 165px !important
  }

  /deep/.ivu-cascader-menu-item{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
    /deep/.ivu-select-item{
      max-width 294px
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
.trees-coadd {
  width: 100%;
  height: 500px;
  border-radius: 4px;
  overflow: hidden;
}
.scollhide {
  width: 100%;
  height: 100%;
  overflow: auto;
  margin-left: 18px;
  padding: 10px 0 10px 0;
  box-sizing: border-box;
}
.content {
  font-size: 12px;
}

.time {
  font-size: 12px;
  color: #2d8cf0;
}

.icons-item {
  float: left;
  margin: 6px 6px 6px 0;
  width: 53px;
  text-align: center;
  list-style: none;
  cursor: pointer;
  height: 50px;
  color: #5c6b77;
  transition: all 0.2s ease;
  position: relative;
  padding-top: 10px;
	font-size: 20px;
}
.search-rule {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f2f2f2;
}
.rule {
  display: flex;
  flex-wrap: wrap;
  max-height: 700px;
  overflow: scroll;
}
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
.rule::-webkit-scrollbar {
  width: 6px;
  height: 6px;
  background-color: #f5f5f5;
}

/*定义滚动条轨道 内阴影+圆角*/
.rule::-webkit-scrollbar-track {
  border-radius: 4px;
  background-color: #f5f5f5;
}

/*定义滑块 内阴影+圆角*/
.rule::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: #555;
}
.rule-list {
  background-color: #f2f2f2;
  width: 32%;
  margin: 5px;
  border-radius: 3px;
  padding: 10px;
  color: #333;
  cursor: pointer;
  transition: all 0.1s;
  overflow: hidden;
}
.rule-list:hover {
  background-color: #c5d1dd;
}
.rule-list div {
  white-space: nowrap;
}
.select-rule {
  background-color: #c5d1dd;
}
.add {
  display: flex;
  align-items: center;
}
</style>
<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>